<?php

class Adminscontroller extends AppController{
	var $name = 'Admins';
	var $uses = array('User');
	var $helpers = array('Form', 'Html2', 'Ajax');
	var $components = array('RequestHandler');
	var $layout = 'admin';

		
	function index(){
		//should be added to before Admin Filter
		$this->checkAdmin();
		$version['scriptaculous'] = $this->RequestHandler->getAjaxVersion();
		$this->set('version', $version);
	}

	function login(){
	//back to admin if user already logged
		if($this->Session->check('User'))
			$this->redirect('/admin');
	
	//init		
		//unbind data not usefull
		$this->User->unbindModel(array('hasMany' => array('Post')));
		$this->layout = 'system';
		
	//request
		if($this->RequestHandler->isPost()){
			//check login / password
			$someone = $this->User->findByUsername($this->data['User']['username']);
		
			if(!empty($someone['User']['username']) && $someone['User']['password'] == x_hashstr($this->data['User']['password'], $someone['User']['salt'])){
				//check beforeSave
				unset($this->data);
				//do not show hashed pass in session var
				unset($someone['User']['password']);
				
				$this->User->id = $someone['User']['id'];
				//write last known ip, last login
				$this->Session->write('last_login', $someone['User']['last_login']);
				$someone['User']['last_login'] = date("Y-m-d H:i:s");
				$someone['User']['last_ip'] = $this->RequestHandler->getClientIP();
				$this->User->save($someone);
				$this->Session->write('User', $someone['User']);
				
				$this->Session->setFlash('You are now logged as '.$someone['User']['username']);
				
				
				if($url = $this->Session->read('url')){
					$this->redirect($url);
				}else{
					$this->redirect('/admin/index');
				}
			}else{
				$this->User->invalidate('username', ' ');
				$this->User->invalidate('password', ' ');
				$this->Session->setFlash('Bad login or password');
				//error : get information : and attempt :: referer, login, ip
			}
		}
	}
	
	function logout(){
		$this->Session->destroy();
		$this->redirect('/');
	}
}
?>
